package com.win.oauth.controller;

import com.fyl.core.response.RS;
import com.win.config.AliyunProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@RestController
@RequestMapping("/oauth/upload")
public class UploadController {

    @Autowired
    AliyunProperties aliyunProperties;

    @PostMapping("/avatar")
    public RS<String> save(@RequestParam MultipartFile file) {

        try {
            String url = aliyunProperties.putObject(UUID.randomUUID().toString() + file.getOriginalFilename(), file.getInputStream());
            return RS.genSuccess(url);
        } catch (IOException e) {
            e.printStackTrace();
            return RS.genFail(e.getMessage());
        }
    }

//    private static String UPLOAD_AVATAR_PATH = "upload/avatar";

//    @RequestMapping(value = "/avatar", method = RequestMethod.POST)
//    public RS<String> uploadImage(@RequestParam MultipartFile file) {
//        try {
//            String name = UUID.randomUUID().toString() + file.getOriginalFilename();
//
//            InputStream inputStream = file.getInputStream();
//            Path directory = Paths.get(UPLOAD_AVATAR_PATH);
//            if (!Files.exists(directory)) {
//                Files.createDirectories(directory);
//            }
//            Files.copy(inputStream, directory.resolve(name));
//            return RS.genSuccess("/" + UPLOAD_AVATAR_PATH + "/" + name);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return RS.genFail(e.getMessage());
//        }
//
//    }

}
